package com.graduationproject.examonline.student.service;

import com.graduationproject.examonline.schoolClass.entity.SchoolClass;
import com.graduationproject.examonline.schoolClass.service.ClassService;
import com.graduationproject.examonline.scorePaper.entity.ScorePaper;
import com.graduationproject.examonline.scorePaper.mapper.ScorePaperMapper;
import com.graduationproject.examonline.student.entity.Student;
import com.graduationproject.examonline.student.mapper.StudentMapper;
import com.graduationproject.examonline.utils.MD5Utils;
import com.graduationproject.examonline.utils.Result;
import com.graduationproject.examonline.utils.SingelKey;
import com.graduationproject.examonline.utils.Token;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.server.ExportException;
import java.util.*;

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassService classService;
    @Autowired
    private ScorePaperMapper scorePaperMapper;

    public Result login(String stuId, String stuPassword) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            String stuPasswordMD5 = MD5Utils.stringToMD5(stuPassword);
            params.put("stuId", stuId);
            params.put("stuPassword", stuPasswordMD5);
            List<Student> record = studentMapper.findStudentByIdAndPassword(params);
            if (record.size() > 0) {
                Map<String, String> info = new HashMap<String, String>();
                info.put("userId", stuId);
                info.put("userName", record.get(0).getStu_name());
                info.put("identity", "student");

                long overDate = new Date().getTime() + 1 * 60 * 60 * 1000;
                String token = Token.createToken(stuId, "student", record.get(0).getStu_name(), new Date(overDate), SingelKey.getInstance().getKey());
                return new Result(0, 200, "登录成功", token, info);
            }
            return new Result(1, 200, "登录失败，密码错误");
        } catch (MyBatisSystemException e) {
            e.printStackTrace();
            return new Result(1, 200, "登录失败，检查身份是否正确");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 200, "登录失败，服务器出错");
        }
    }

    public int addStudent(Map<String, Object> params) {
        try {
            params.replace("stuPassword", MD5Utils.stringToMD5((String) params.get("stuPassword")));
            studentMapper.insertStudent(params);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public Result updatePassword(String stuId, String prePassword, String nextPassword) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            String prePasswordMD5 = MD5Utils.stringToMD5(prePassword);
            params.put("stuId", stuId);
            params.put("stuPassword", prePasswordMD5);
            List<Student> record = studentMapper.findStudentByIdAndPassword(params);
            if (record.size() > 0) {
                params = new HashMap<String, Object>();
                params.put("stuId", stuId);
                params.put("stuPassword", MD5Utils.stringToMD5(nextPassword));
                studentMapper.editStudentById(params);
                return new Result(0, 200, "修改成功");
            } else {
                return new Result(1, 200, "密码错误，修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "未知错误，修改失败");
        }
    }

    public Result updateName(String stuId, String stuName) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("stuId", stuId);
            params.put("stuName", stuName);
            studentMapper.editStudentById(params);
            return new Result(0, 200, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "未知错误，修改失败");
        }
    }

    public Result getUserInfo(String stuId) {
        try {
            List<Student> resultList = studentMapper.findStudentById(stuId);
            if (resultList.size() > 0) {
                Student stu = resultList.get(0);
                String stuName = stu.getStu_name();
                String[] classIdList = null;
                if (stu.getClass_id() != null) {
                    classIdList = stu.getClass_id().split(",");
                }
                String[] noticeIdList = null;
                if (stu.getNotice_id() != null) {
                    noticeIdList = stu.getNotice_id().split(",");
                }
                List<String> classNameList = new ArrayList<>();
                if (classIdList.length > 0) {
                    // 查询班级名称
                    for (int index = 0; index < classIdList.length; index += 1) {
                        Result classList = classService.findClassById(classIdList[index]);
                        if (classList.getCode() == 200 && classList.getStatus() == 0) {
                            List<SchoolClass> schoolClassList = (List<SchoolClass>) (classList.getData());
                            classNameList.add(schoolClassList.get(0).getClass_name());
                        }
                    }
                }
                if (noticeIdList != null) {
                    if (noticeIdList.length > 0) {
                        // 查询通知
                    }
                }
                Map<String, Object> stuInfo = new HashMap<String, Object>();
                stuInfo.put("stuId", stuId);
                stuInfo.put("stuName", stuName);
                stuInfo.put("classNameList", classNameList);
                stuInfo.put("noticeList", noticeIdList);
                return new Result(0, 200, "查询成功", stuInfo);
            } else {
                return new Result(1, 200, "未找到该用户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "未知错误，查询失败");
        }
    }

    public Result getAllUserInfo() {
        try {
            List<Student> studentList = studentMapper.findAllStudent();
            return new Result(0, 200, studentList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "error");
        }
    }

    public Result updateById(Map<String, Object> p) {
        try {
            String stu_id = (String) p.get("stuId");
            String next_stu_id = (String) p.get("nextStuId");
            String pass = (String) p.get("stuPassword");
            if (pass != null) {
                pass = MD5Utils.stringToMD5(pass);
                p.put("stuPassword", pass);
            }
            if (p.get("deleted") != null) {
                if ((int) p.get("deleted") == 1) {
                    p.put("nextStuId", stu_id + "_deleted_" + new Date().getTime());
                }
            }
            studentMapper.editStudentById(p);
            if (next_stu_id != null) {
                List<ScorePaper> scorePaperList = scorePaperMapper.getScoreInfoByStuId(stu_id);
                for (int i = 0; i < scorePaperList.size(); i++) {
                    scorePaperMapper.updateStuId(stu_id, next_stu_id);
                }
            }
            return new Result(0, 200, "ok");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "error");
        }
    }

    public Result insertStudet(Map<String, Object> p) {
        try {
            Map<String, Object> p2 = new HashMap<String, Object>();
            String stu_id = (String) p.get("nextStuId");
            String pass = (String) p.get("stuPassword");
            String class_id = (String) p.get("classId");
            String stuName = (String) p.get("stuName");
            pass = MD5Utils.stringToMD5(pass);

            p2.put("stu_id", stu_id);
            p2.put("stu_password", pass);
            p2.put("stu_name", stuName);
            p2.put("class_id", class_id);
            p2.put("deleted", 0);

            studentMapper.insertStudent(p2);
            return new Result(0, 200, "ok");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, 500, "error");
        }
    }

}
